﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows.Forms;

namespace Brain.Windows
{
    public class PropertyValue
    {
        delegate void SetControlValueCallback(Control oControl, string propName, object propValue);

        /// <summary>
        /// Set a value to a Property (thread-safe)
        /// </summary>
        /// <param name="oControl"></param>
        /// <param name="propName"></param>
        /// <param name="propValue"></param>
        public static void SetControlPropertyValue(Control oControl, string propName, object propValue)
        {
            if (oControl.InvokeRequired)
            {
                SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
                oControl.Invoke(d, new object[] { oControl, propName, propValue });
            }
            else
            {
                Type t = oControl.GetType();
                PropertyInfo[] props = t.GetProperties();
                foreach (PropertyInfo p in props)
                {
                    if (p.Name.ToUpper() == propName.ToUpper())
                    {
                        p.SetValue(oControl, propValue, null);
                    }
                }
            }
        }

        /// <summary>
        /// Gets a value from a Property (thread-safe)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oControl"></param>
        /// <param name="propName"></param>
        /// <returns></returns>
        public static T GetControlPropertyValue<T>(Control oControl, string propName)
        {
            Type t = oControl.GetType();
            PropertyInfo[] props = t.GetProperties();
            foreach (PropertyInfo p in props)
            {
                if (p.Name.ToUpper() == propName.ToUpper())
                {
                    object obj = p.GetValue(oControl, null);
                    return (T)obj;
                }
            }
            return default(T);
        }
    }
}
